package com.adk.backend.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 条形码工具类
 */
@Slf4j
@Component
public class BarcodeUtil {
    
    /**
     * 生成Code128条形码（不包含文本）
     * @param barcodeContent 条形码内容
     * @param savePath 保存路径（相对于项目根目录，如 "uploads/barcode/ctn_label"）
     * @return 生成的条形码文件路径
     */
    public String createBarcodeWithoutText(String barcodeContent, String savePath) {
        try {
            // 创建保存目录
            File dir = new File(savePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 条形码参数
            int width = 200;
            int height = 80;
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1);
            
            // 生成条形码
            Code128Writer writer = new Code128Writer();
            BitMatrix bitMatrix = writer.encode(barcodeContent, BarcodeFormat.CODE_128, width, height, hints);
            
            // 创建图片
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = image.createGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, width, height);
            graphics.setColor(Color.BLACK);
            
            // 绘制条形码
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    if (bitMatrix.get(x, y)) {
                        graphics.fillRect(x, y, 1, 1);
                    }
                }
            }
            
            graphics.dispose();
            
            // 保存图片
            String fileName = barcodeContent + ".png";
            File barcodeFile = new File(dir, fileName);
            ImageIO.write(image, "png", barcodeFile);
            
            // 返回文件路径（相对于项目根目录）
            return savePath + "/" + fileName;
        } catch (IOException e) {
            log.error("生成条形码失败: barcodeContent={}, savePath={}", barcodeContent, savePath, e);
            throw new RuntimeException("生成条形码失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("生成条形码失败: barcodeContent={}, savePath={}", barcodeContent, savePath, e);
            throw new RuntimeException("生成条形码失败：" + e.getMessage());
        }
    }
    
    /**
     * 生成Code128条形码（包含文本）
     * @param barcodeContent 条形码内容
     * @param savePath 保存路径（相对于项目根目录，如 "uploads/barcode/ctn_label"）
     * @return 生成的条形码文件路径
     */
    public String createBarcodeWithText(String barcodeContent, String savePath) {
        try {
            // 创建保存目录
            File dir = new File(savePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 条形码参数
            int width = 200;
            int height = 100; // 增加高度以容纳文本
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1);
            
            // 生成条形码
            Code128Writer writer = new Code128Writer();
            BitMatrix bitMatrix = writer.encode(barcodeContent, BarcodeFormat.CODE_128, width, height - 20, hints);
            
            // 创建图片
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = image.createGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            
            // 填充白色背景
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, width, height);
            
            // 绘制条形码
            graphics.setColor(Color.BLACK);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height - 20; y++) {
                    if (bitMatrix.get(x, y)) {
                        graphics.fillRect(x, y, 1, 1);
                    }
                }
            }
            
            // 绘制文本
            graphics.setFont(new Font("Arial", Font.PLAIN, 12));
            FontMetrics fm = graphics.getFontMetrics();
            int textWidth = fm.stringWidth(barcodeContent);
            int textX = (width - textWidth) / 2;
            int textY = height - 5;
            graphics.drawString(barcodeContent, textX, textY);
            
            graphics.dispose();
            
            // 保存图片
            String fileName = barcodeContent + ".png";
            File barcodeFile = new File(dir, fileName);
            ImageIO.write(image, "png", barcodeFile);
            
            // 返回文件路径（相对于项目根目录）
            return savePath + "/" + fileName;
        } catch (IOException e) {
            log.error("生成条形码失败: barcodeContent={}, savePath={}", barcodeContent, savePath, e);
            throw new RuntimeException("生成条形码失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("生成条形码失败: barcodeContent={}, savePath={}", barcodeContent, savePath, e);
            throw new RuntimeException("生成条形码失败：" + e.getMessage());
        }
    }
}

